﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace Catalyst.Linq
{
	internal class ExpressionTreeModifier : ExpressionVisitor
	{
		private IQueryable queryableActiveRecords;

		private Type _elementType;

		internal ExpressionTreeModifier(IQueryable activeRecords, Type elementType)
		{
			_elementType = elementType;
			this.queryableActiveRecords = activeRecords;
		}

		internal Expression CopyAndModify(Expression expression)
		{
			return this.Visit(expression);
		}

		protected override Expression VisitConstant(ConstantExpression c)
		{
			// Replace the constant QueryableTerraServerData arg with the queryable Place collection.
			if (c.Type == typeof(Catalyst.Linq.Query<>).MakeGenericType(_elementType))
				return Expression.Constant(this.queryableActiveRecords);
			else
				return c;
		}
	}
}
